/**
 * Created by lxg on 2016/12/20.
 */
/**
 * 文件对象
 */
var fileObj = {
    upLoadSize : 0
};
/**
 * 保存gif和压缩包 新旧名称的对象
 */
var uploadFileObj = {
	gifName : null,
	gifNewName : null,
	isGifUpload: 0,//0:未上传 1:上传
	zipName : null,
	zipNewName: null,
	isZipUpload:0//0:未上传 1:上传
	
};
/**
 * 上传配置
 */
var opt = {
    blodSize : 1024*1024*10, //文件分片大小
    method : 'post', //请求方式
    fileObjName : 'file', //后台接收的文件名（后台使用spring mvc时此项不必要）
    uploadUrl : '/pestdiagnosis/sys/pest/uploadFile1', //文件上传地址
    getUploadedSizeUrl : '/pestdiagnosis/sys/pest/uploadSize' //获取文件已上传大小地址
};
$(function () {

    //压缩包上传
    $("#video").change(function (e) {
    	if(typeof(e.target.files[0]) != "undefined"){
    		var file = e.target.files[0];
    		fileObj.name = file.name;//文件原来的名称
    		fileObj.newName = new Date().getTime()+file.name;//服务器中保存文件的名称
    		fileObj.size = file.size;//文件初始大小
    		fileObj.oldFile = file;
    		fileObj.upLoadSize = 0;

    		uploadFileObj.zipName = file.name;
    		uploadFileObj.zipNewName = fileObj.newName;

    		$("#newName").val(fileObj.newName);


    		afterChange(file,'video');
    		
    	}
    });


    //选择文件之后
    var afterChange = function(file,id){
    	
    	var str = '<div style="padding:10px 10px;"><span style="font-weight:bold">文件名称:</span><span id="filename">'+fileObj.name+'</span><p><div class="progress" style="width:390px;">'
  		  +'<div style="color: #20FF11;" id="progress" class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" '
  		  +'aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width:0%;">'
  		  +'</div></div>'
  		  +'<center style="padding:20px 20px;"><button class="btn btn-primary fileupload">上传</button><p><span id="msg" style="color:red;"></span></center></div>';
    	

    	layer.open({
    		  type: 1,
    		  skin: 'layui-layer-rim', //加上边框
    		  area: ['420px', '240px'], //宽高
    		  content: str
    		});
    	
    	$('.fileupload').on('click',(function(){
 			return function(){upload(id);}
 		})(file));

    }

    //点击上传按钮事件后响应函数
    var upload = function(id){

    	sendBlob(opt.uploadUrl,getBlod(fileObj.oldFile),{'name':fileObj.name,'newName':fileObj.newName});
    }

    /**
     * 分割文件
     * @param file
     * @returns {string|Blob|Array.<T>|ArrayBuffer|*}
     */
    var getBlod = function (file) {
    	var upLoadSize = 0;
    	if(!fileObj.upLoadSize > 0){
    		upLoadSize = getUpLoadSize(file);
    	}else{
    		upLoadSize = fileObj.upLoadSize;
    	}

        var BoldFile = file.slice(upLoadSize,upLoadSize+opt.blodSize);
        return BoldFile;
    }

    /**
     * 获取已上传文件大小
     * @param file
     * @returns {number}
     */
    var getUpLoadSize = function (file) {
        var uploadedSize = 0;
        $.ajax({
            url : opt.getUploadedSizeUrl,
            data : {'name':fileObj.name,'newName':fileObj.newName,'size':fileObj.size},
            async : false,
            type : 'POST',
            success : function(returnData){
            	onProgress(file, returnData, fileObj.size);
                uploadedSize = returnData;
            }
        });

        return uploadedSize;
    }

    /**
     * 上传文件块
     * @param url
     * @param file
     * @param formdata
     */
    var sendBlob = function(url,file,formdata){
        var xhr=new XMLHttpRequest();
        xhr.open(opt.method, url, true);
        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        var fd = new FormData();
        fd.append(opt.fileObjName,file);
        if(formdata){
            for(key in formdata){
                fd.append(key,formdata[key]);
            }
        }
        xhr.send(fd);

        xhr.upload.addEventListener("progress", function(e) {
            onProgress(file, e.loaded, fileObj.size);
        }, false);

        xhr.onreadystatechange = function(e) {
            if (xhr.readyState == 4) {
                fileObj.uploadOver = true;
                if (xhr.status == 200) {
                    fileObj.upLoadSize = getUpLoadSize(file);
                    if(fileObj.upLoadSize < fileObj.size){
                        sendBlob(opt.uploadUrl,getBlod(fileObj.oldFile),{'name':fileObj.name,'newName':fileObj.newName});
                    }
                }
            }
        }
    }

    /**
     * 进度条处理
     * @param file
     * @param loaded
     * @param size
     */
    var onProgress = function (file, loaded, size) {
        console.log(loaded+"====="+size);
    	// console.log("本次已上传："+loaded)
    	// console.log("upLoadSize:"+fileObj.upLoadSize)
    	
    	// var p = (((parseInt(loaded)+parseInt(fileObj.upLoadSize))/parseInt(fileObj.size))*100).toFixed(2);
    	var p = (loaded/size*100).toFixed(2)
        console.log("p="+p);
        $("#progress").css('width',p+'%');
    	var percentText = p >= 100 ? '100.00%' : p +'%';
    	if(percentText == '100.00%'){
    		$("#msg").text("上传成功！");
    		setTimeout(function(){layer.closeAll();},2000);
    	}
        $("#msg").text("已上传"+p+"%");
    	// $("#bfb").html(percentText);
    }

});
